import { v4 as uuidv4 } from 'uuid';

export default {
  use(app, knex){

    //新增通道
    app.post('/chanel/add', function(req, res){
      knex('chanel')
      .where('parent_id', '=', req.body.parent_id)
      .andWhere('com', '=', req.body.com)
      .then(rows => {
        if(rows.length > 0){
          res.send({
            code: 1,
            message: `通道端口${req.body.com}已存在, 请修改后重新提交`
          })
        }else{
          knex('chanel')
          .insert({id: uuidv4(), ...req.body})
          .then(row=>{
            res.send({
              code: 0,
              message: '新增通道成功'
            })
          })
          .catch(err=>{
            console.log(err)
            res.send({
              code: 1,
              message: err
            })
          })  
        }
      })
    })


    //查询通道
    app.post('/chanel', function(req, res){
      knex('chanel')
      .where({'parent_id': req.body.parent_id})
      .select('*').then(rows=>{
        res.send({
          code: 0,
          data: rows
        })
      })  
      .catch(err => {
        console.log(err)
        res.send({
          code: 1,
          message: err
        })
      })
    })

    
    //删除通道
    app.post('/chanel/del', function(req, res){
      knex
      .raw(`PRAGMA foreign_keys=ON`)
      .then(() => {
        knex
        .raw(`delete from chanel where id="${req.body.id}"`)
        .then( rows =>{
          res.send({
            code: 0,
            data: '删除通道成功'
          })
        })
      })
    })

    
    //更新通道
    app.post('/chanel/update', function(req, res){
      const data = req.body;
      const id = data.id;
      delete data.id;
      knex('chanel')
      .where('id', '=', id)
      .update({
        ...data
      })
      .then(row => {
        res.send({
          code: 0,
          data: '更新通道成功'
        })
      })
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })
  }
}

